package com.moss.cloud.auth.api.utils;

import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.exception.BaseException;
import com.moss.cloud.common.core.exception.SystemErrorType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.InvalidSignatureException;
import org.springframework.security.jwt.crypto.sign.MacSigner;

import java.util.Optional;
@Slf4j
public class JwtAccessToken {
    private static final int BEARER_BEGIN_INDEX = 7;
    /**
     * jwt验签
     */
    private static MacSigner verifier;
    public static boolean invalidJwtAccessToken(String clientToken) {
        log.info("验证token:{}",clientToken);
        verifier = Optional.ofNullable(verifier).orElse(new MacSigner(Constant.JWT_KEY));
        //是否无效true表示无效
        boolean invalid;
        try {
            Jwt jwt = getJwt(clientToken);
            jwt.verifySignature(verifier);
            invalid = Boolean.FALSE;
        } catch (InvalidSignatureException | IllegalArgumentException ex) {
            log.info("用户令牌已过期或签名错误");
            throw new BaseException(SystemErrorType.INVALID_SIGNATURE);
        }
        return invalid;
    }

    public static Jwt getJwt(String authentication) {
        return JwtHelper.decode(StringUtils.substring(authentication, BEARER_BEGIN_INDEX));
    }
}
